package com.wlj.web.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fasterxml.jackson.annotation.JsonView;
import com.wlj.dto.UserRoleDTO;
import com.wlj.exception.CustomException;
import com.wlj.form.UserAddForm;
import com.wlj.pojo.TbRole;
import com.wlj.pojo.TbUser;
import com.wlj.service.RoleService;
import com.wlj.service.UserService;
import com.wlj.vo.JsonRes;
import com.wlj.vo.view.GeneralViews;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;
    /**
     * 管理员页面
     * @return
     */
    @GetMapping("/users.html")
    public String users(Model model){
        List<UserRoleDTO> userRoleDTOS = userService.listUsersAndRole();
        model.addAttribute("users",userRoleDTOS);
        List<TbRole> allRoles = roleService.getAllRoles();
        List<TbRole> roles = allRoles.stream().filter(e -> !e.getRoleName().equals("root")).collect(Collectors.toList());
        model.addAttribute("roles",roles);
        model.addAttribute("action","/admin/users");
        return "/admin/users";
    }

    @GetMapping("/roles.html")
    public String roles(Model model){
        return "/admin/roles";
    }




    @GetMapping("/editAdminModal")
    public String editAdminModal(Model model, Authentication curUser,
                                 @RequestParam("userId") Integer userId){
        //编辑目标用户
        UserRoleDTO targetUser = userService.getUserAndRoleById(userId);

        //当前登录用户是否是root
        UserRoleDTO userAndRoles = userService.getUserAndRoles(curUser.getName());
        boolean root=false;
        for (TbRole role : userAndRoles.getRoles()) {
            if(role.getRoleName().equalsIgnoreCase("root")){
                root=true;
                break;
            }
        }
        //编辑他人
        if(!StringUtils.equals(curUser.getName(),targetUser.getUsername())&&!root){
            throw new CustomException("1002","除非超级管理员,不能编辑除自己外的用户");
        }

        List<TbRole> allRoles = roleService.getAllRoles();
        allRoles = allRoles.stream().filter(e -> !e.getRoleName().equals("root")).collect(Collectors.toList());
        //所有角色
        model.addAttribute("roles",allRoles);
        //编辑目标用户是否是当前登录用户
        model.addAttribute("own",StringUtils.equals(curUser.getName(),targetUser.getUsername()));
        //当前登录用户是否是root
        model.addAttribute("root",root);
        //编辑目标用户
        model.addAttribute("user",targetUser);
        return "/admin/editAdmin";
    }




    @PostMapping("/users")
    @ResponseBody
    @JsonView(GeneralViews.IErrorView.class)
    public JsonRes addUser(@Valid UserAddForm userAddForm){
        userService.addUser(userAddForm);
        return JsonRes.success();
    }

    @DeleteMapping("/users")
    @ResponseBody
    @JsonView(GeneralViews.IErrorView.class)
    public JsonRes delUser(@RequestBody Map<String,Object> params){
        UserRoleDTO user = userService.getUserAndRoleById(Integer.valueOf((String) params.get("userId")));
        for (TbRole role : user.getRoles()) {
            if(role.getRoleName().equalsIgnoreCase("root")){
                throw new CustomException("4002","不能删除超级管理员");
            }
        }
        userService.delUser(Integer.valueOf((String) params.get("userId")));
        return JsonRes.success();
    }


}
